package org.jeecg.modules.system.controller;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.jeecg.common.util.MinioUtil;
import org.jeecg.common.util.oConvertUtils;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.HandlerMapping;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@RestController
@RequestMapping("/minio")
public class FileController {

	// http://localhost:8080/sqsyx/minio/sqsyx/temp/IMG20220518203945_1666148118203.jpg
	// 图片访问需要验证权限，统一走程序判定
	// TODO 上传场景需要区分临时、敏感信息（个人 是否公开）
	
	@GetMapping(value = "/sqsyx/**")
    public void viewTmp(HttpServletRequest request, HttpServletResponse response) {
    	// ISO-8859-1 ==> UTF-8 进行编码转换
        String imgPath = extractPathFromPattern(request);
        if(oConvertUtils.isEmpty(imgPath) || imgPath=="null"){
            return;
        }
        System.out.println(imgPath);
        /**
         * 文件时效性链接获取
         * 1.获取文件参数、相对路径
         * 2.获取文件所属权,公开性（针对头像等公开信息，直接放开）
         * 3.校验是否个人拥有访问权限(防止单一token爆破其他附件)
         * 
         */
     // 其余处理略
        InputStream inputStream = null;
        OutputStream outputStream = null;
        // 调整为默认授权链接
        //String imgTmpUrl = MinioUtil.getObjectUrl("sqsyx", imgPath, 30);
        try {
        	// 准备采用获取临时访问链接方式，但是返回链接是http格式
			//response.sendRedirect(imgTmpUrl);
        	response.setContentType("application/force-download");
            response.addHeader("Content-Disposition", "attachment;fileName=" + new String(imgPath.getBytes("UTF-8"),"iso-8859-1"));
            inputStream = new BufferedInputStream(MinioUtil.getMinioFile("sqsyx", imgPath));
            outputStream = response.getOutputStream();
            byte[] buf = new byte[1024];
            int len;
            while ((len = inputStream.read(buf)) > 0) {
                outputStream.write(buf, 0, len);
            }
            response.flushBuffer();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    log.error(e.getMessage(), e);
                }
            }
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    log.error(e.getMessage(), e);
                }
            }
		}
    }
	
	/**
     *  把指定URL后的字符串全部截断当成参数
     *  这么做是为了防止URL中包含中文或者特殊字符（/等）时，匹配不了的问题
     * @param request
     * @return
     */
    private static String extractPathFromPattern(final HttpServletRequest request) {
        String path = (String) request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE);
        String bestMatchPattern = (String) request.getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE);
        return new AntPathMatcher().extractPathWithinPattern(bestMatchPattern, path);
    }
}
